const fs = require('fs');
const query = require('../utils/query')
var request = require('request');
var rp = require('request-promise');

// select * from bussiness_product where product_id in ('009', '014', '025', '028', '033', '031', '021', '020', '054', '050', '019', '022', '032')

let iconSql = fs.createWriteStream(`./sql/icon.sql`);
let notProcessProductId = [];
const host = 'http://10.112.73.28:8803';
const uploadUrl =   host + '/basic/upload';

(async () => {
    let updateSql = "";
    let  items = await query("select product_id from device_types2 where product_id is Not null;")

    for(let i = 0, l = items.length; i< l;i++) {
        let item = items[i]
        let icons = await query(`select product_id, main_url from t_product_icon where icon_type = "control" and product_id = (${item.product_id});`)
        if(icons != null && icons.length > 0) {
            icon = icons[0]
            var options = {
                method: 'POST',
                uri: uploadUrl,
                formData: {
                    file: {
                        value: request(icon.main_url),
                        options: {
                            filename: `${item.product_id}.png`,
                            contentType: 'image/png'
                        }
                    }
                }
            };
            let body = await rp(options)
            let data = JSON.parse(body)
            if(data.code === "0") {
                let fileId = data.data.fileId;
                updateSql += `update device_types2 set file_id = "${fileId}" where product_id = ${item.product_id};` + '\n'
            } else {
                console.log("文件上传失败", item )
            }
        } else {
            notProcessProductId.push(item.product_id)
        }
    }
    iconSql.write(updateSql);
    console.log("updateSql", updateSql)
    console.log("没有找到icon, productId", notProcessProductId)
})();


async function sleep() {
    await setTimeout(function () {
        console.log('这是来自3s之后的问好');
    },3000)
    console.log("hello")
}










